package cn.huixh.blindbox.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author huixh
 * @version 1.0
 * @date 2022/5/10 9:53
 */
@Slf4j
@Component
public class ToolsUtil {

    /**
     * 字节转 MD5
     *
     * @param bytes 字节
     * @return MD5
     */
    public String getFileMd5(byte[] bytes) {
        return DigestUtils.md5DigestAsHex(bytes);
    }

    public File transferToFile(MultipartFile multipartFile) {
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            assert originalFilename != null;
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[ 0 ], filename[ 1 ]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch ( IOException e ) {
            log.error("MultipartFile 文件转换失败！信息：{}", e.getMessage());
        }
        return file;
    }

    /**
     * 获取完整 url 路径
     *
     * @return url 路径
     */
    public String getFullUrl() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();
        return request.getScheme() + "://" + request.getHeader("Host") + request.getContextPath();
    }

    protected RequestAttributes getRequestAttributes() {
        return RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取 response
     *
     * @return response
     */
    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) getRequestAttributes()).getResponse();
    }

    /**
     * 获取 request
     *
     * @return request
     */
    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) getRequestAttributes()).getRequest();
    }

    /**
     * 获取 输出流
     *
     * @return 输出流
     */
    public OutputStream getResponseOutput() {
        try {
            return getResponse().getOutputStream();
        } catch ( IOException e ) {
            log.error("获取 response output 失败！信息：{}", e.getMessage());
            return new ByteArrayOutputStream();
        }
    }
}
